package com.ls.lserp.modules.material.web;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.excel.ExportExcel;
import com.ls.lserp.common.utils.excel.ImportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.material.entity.StockCheck;
import com.ls.lserp.modules.material.entity.StockCheckExportEntity;
import com.ls.lserp.modules.material.service.StockCheckService;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;

import freemarker.template.Configuration;
import freemarker.template.utility.DateUtil;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/stock/check/")
public class StockCheckController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private StockCheckService stockCheckService;
	@Autowired
	Configuration freemarkerConfiguration;

	/*@ModelAttribute
	public StockCheck get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return stockCheckService.get(Long.parseLong(id));
		} else {
			// 若为空，实例化
			return new StockCheck();
		}
	}*/

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("stock:check:view")
	@RequestMapping(value = { "" })
	public String list(StockCheck stockCheck, Model model) {
		List<StockCheck> warehouselist =  stockCheckService.findWarehouseList(stockCheck);
		model.addAttribute("warehouselist", warehouselist);
		// 画面跳转
		return "modules/material/stockCheck";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param inventoryRequest
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("stock:check:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(StockCheck stockCheck, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "stockCheck");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&warehouseID=");
		searchParam.append(stockCheck.getWarehouseID());
		
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<StockCheck> page = stockCheckService.findList(new Page<StockCheck>(request, response),stockCheck);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("stockChecks", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		map.put("springMacroRequestContext", new RequestContext (request));
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("stockCheck.ftl"), map);
		listMap.put("stockCheck", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	

	/**
     * 导出定制项目单耗
     *
     * @param response
     * @param styleOptionEntity
     * @return
     */
    @RequiresPermissions("stock:check:view")
    @RequestMapping(value = "exportFile")
    public String exportFile(StockCheck stockCheck, HttpServletResponse response) {
        try {
            String fileName =  stockCheck.getWarehouseName() + DateUtils.getDate("yyyyMMdd") + "库存盘点.xlsx";
            SXSSFWorkbook wb = new SXSSFWorkbook ();
            List<StockCheckExportEntity> stockCheckList = stockCheckService.makeStockCheckList (stockCheck);

            // custom_msg04 :库存盘点
            new ExportExcel ("库存盘点", wb, getText ("take_check"), StockCheckExportEntity.class, 2).setDataList (stockCheckList);
            response.reset ();
            response.setContentType ("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding ("UTF-8");
            response.setHeader ("Content-Disposition", "attachment; filename=" + new String (fileName.getBytes (), "ISO-8859-1"));
            wb.write (response.getOutputStream ());
            return null;
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
        }

        // 提示错误信息
        return renderString (response, AjaxDone.error (getText ("System_error_please_contact_your_administrator")));

    }
    

   /**
    * 保存信息
    * @param enchase
    * @param request
    * @param model
    * @param response
    * @return
    * @throws ResourceException 
    */
   @RequiresPermissions("stock:check:edit")
   @RequestMapping(value = "saveData")
   @ResponseBody
   public String saveData(StockCheck stockCheck, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws Exception {
	   try {
		   // 保存
		   stockCheckService.saveData(stockCheck);
		} catch (Exception e) {
			 // 记录日志
            logger.error (e.getMessage (), e);
			return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}
   	
   	   // 保存成功返回提示信息
       return renderString(response,AjaxDone.ok(getText( "stockCheck_msg_saveSuccess")));
   }
   
   /**
    * 保存信息
    * @param enchase
    * @param request
    * @param model
    * @param response
    * @return
    * @throws ResourceException 
    */
   @RequiresPermissions("stock:check:edit")
   @RequestMapping(value = "checkComplete")
   @ResponseBody
   public String checkComplete(StockCheck stockCheck, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws Exception {
	   try {
		   // 保存
		   stockCheckService.checkComplete(stockCheck);
		} catch (Exception e) {
			 // 记录日志
            logger.error (e.getMessage (), e);
			return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}
   	
   	   // 保存成功返回提示信息
       return renderString(response,AjaxDone.ok(getText( "stockCheck_msg_saveSuccess")));
   }
   
	/**
    * 进入查看页面
    * @param inventoryRequest
    * @param model
    * @return
    */
   @RequiresPermissions("stock:check:view")
   @RequestMapping(value = "show")
   public String show(StockCheck stockCheck, Model model) {
	   
	   List<StockCheck> takeDetailList = stockCheckService.findTakeDetailList(stockCheck);
       // 将查询结果赋值mvc model层返回jsp页面
       model.addAttribute("stockCheck", stockCheck);
       model.addAttribute("takeDetailList", takeDetailList);
       
       // 返回页面地址
       return "modules/material/stockCheckShow";
   }
   
   /**
    * 进入查看页面
    * @param inventoryRequest
    * @param model
    * @return
    */
   @RequiresPermissions("stock:check:view")
   @RequestMapping(value = "create")
   public String create(StockCheck stockCheck, Model model) {
	   
	   List<StockCheck> warehouselist =  stockCheckService.findWarehouseList(stockCheck);
       // 将查询结果赋值mvc model层返回jsp页面
       model.addAttribute("stockCheck", stockCheck);
       model.addAttribute("warehouselist", warehouselist);
       
       // 返回页面地址
       return "modules/material/stockCheckCreat";
   }
   
   
   /**
	 * @Title: 导入画面
	 * @return url
	 */
	@RequiresPermissions("stock:check:edit")
	@RequestMapping(value = { "importExcel" })
	public String importExcel(Long stockCheckID,Model model) {
		model.addAttribute("stockCheckID",stockCheckID);
		// 画面跳转
		return "modules/material/uploadFileTakeCheck";
	}
    
	/**
	 * 导入Excel
	 *
	 * @param file
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "insertExcelData", method = RequestMethod.POST)
	@ResponseBody
	public String insertExcelData(MultipartFile file,Long id,HttpServletResponse response) throws Exception {
		String oldFlg = "false";
		List<StockCheck> stockCheckList = new ArrayList<>();
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			Workbook workbook = ei.wb;
			Sheet st = workbook.getSheetAt(0);
			int rowmun = st.getPhysicalNumberOfRows();
			String cellStr;
			StockCheck stockCheck = new StockCheck();
			for (int i = 2; i < rowmun; i++) {
					// 仓库ID
					cellStr = getCellValue(st.getRow(i).getCell(0));
					stockCheck.setWarehouseID(Long.parseLong(cellStr.split(":")[0]));
					// 货架ID
					cellStr = getCellValue(st.getRow(i).getCell(1));
					stockCheck.setRackID(Long.parseLong(cellStr.split(":")[0]));
					// 面料ID
					cellStr = getCellValue(st.getRow(i).getCell(2));
					stockCheck.setMaterialId(Long.parseLong(cellStr.split(":")[0]));
					// 实际数量
					cellStr = getCellValue(st.getRow(i).getCell(5));
					if (cellStr == null || "".equals(cellStr)) {
						return renderString(response,AjaxDone.error(getText("stockCheck_failed_import")+getText("stockCheck_null_realQuantity")));
					}
					stockCheck.setRealQuantity(new BigDecimal(cellStr));
					stockCheckList.add(stockCheck);
					stockCheck = new StockCheck();
			}
			stockCheck.setId(id);
			stockCheck.setStockCheckList(stockCheckList);
			// excel数据导入
			stockCheckService.insertExcelData(stockCheck); 
			oldFlg = "true";
		} catch (Exception e) {
			logger.error (e.getMessage (), e);
			// 返回提示信息
			return renderString(response, oldFlg);
		}
		return renderString(response, oldFlg);
	}
	
	/**
	 * 获取单元格的值
	 * 
	 * @param cell
	 * @return
	 */
	public String getCellValue(Cell cell) {
		if (cell == null)
			return "";
		if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
			return cell.getStringCellValue();
		} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
			return cell.getCellFormula();
		} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			return cell.getNumericCellValue() + "";
		}
		return "";
	}

}
